package outputstream_;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author DCSGO
 * @version 1.0
 * 模拟实现文件的拷贝
 */
public class FileCopy {
    @Test
    public void copy() {
        String srcFilePath = "D:\\src\\shroud.jpg";
        String destFilePath = "E:\\dest\\shroudCopy.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            byte[] buf = new byte[1024];
            int readLen;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //拷贝的文件大小不一定是 1024 的整数倍故用 write(byte b[], int off, int len)
                fileOutputStream.write(buf, 0, readLen);
            }
            System.out.println("拷贝成功");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

